﻿#light
open System.Text.RegularExpressions
open Common

///Replace all the underscores with spaces
let public ReplaceUnderscoresWithSpaces (original : string) = original.Replace("_", " ")

///Replace the wildcard '%' to the regular expression wildcard
let private ReplacePatternWildcard(pattern : string) = pattern.Replace("%", ".*")

///Get the Regex with the passed pattern primed for wildcards
let private GetWildCardRegex (pattern : string) = pattern |> System.Text.RegularExpressions.Regex.Escape 
                                                          |> ReplacePatternWildcard 
                                                          |> GetRegex

///Perform a replace a wildcard of '%'
let public ReplaceWildcard (original : string) 
                           (pattern : string) 
                           (substitution : string) = GetWildCardRegex(pattern).Replace(original, substitution)
                                               
///Get the Regex for finding dashes
let private GetDashRex = "\S-\S" |> GetRegex  

///Get a " " if teh passed string does not start with a " ", otherwise just return the empty string ""
let private GetSpaceIfNotAtStart (word : string) = 
    if ( word.[0] = ' ' ) then
        ""
    else
        " "
        
///Get a " " if the passed string does not end with a " ", otherwise just return the empty string ""
let private GetSpaceIfNotAtEnd (word : string) =
    if ( word.[word.Length - 1] =  ' ' ) then
        ""
    else
        " "
        
///Recusively combine an array of string so that they are in the form string1 - string2 - string3 - etc...
let rec private RecursiveSpaceDashSpace (splitStrings : string list) =
    if ( splitStrings.Length = 0) then
        ""
    else
        let leadString = splitStrings |> List.hd 
        let SpaceForEnd = 
            if (splitStrings.Length = 1) then
                ""
            else
                GetSpaceIfNotAtEnd leadString
        GetSpaceIfNotAtStart(leadString) + leadString + SpaceForEnd + "-" + RecursiveSpaceDashSpace(List.tl splitStrings)

///Replace all *-* with * - *
let public ReplaceDashesWithSpaceDashSpace (original : string) = 
    if (GetDashRex.IsMatch(original) = false) then
        original
    else
        let splitStrings = original.Split([|'-'|]) 
        let unTrimmed = splitStrings |> List.of_array |> RecursiveSpaceDashSpace 
        unTrimmed.[1 .. unTrimmed.Length-2] //Get rid of the leading space and last dash
    
